<template>
  <div>
    <!-- LayIM即时通讯 2018/3/8 18:28 zhangQ -->
  </div>
</template>
<script>
  import { layuiInit, deleteCurrentChatlog, layimConf } from './main'
  import { getNewMsg, getChatInfo, sendTextMsg } from '@api/common/index'
  import moment from 'moment'

  let contentType = { // 内容类型
    txt: 1,
    voice: 2,
    image: 3
  }

  export default {
    name: 'index',
    data () {
      let layim = null
      let newMsgArray = [] // 不停的取新消息会造成消息重复，所以加上列表
      let currentWinId = '' // 当前窗口
      let datas = { layim, newMsgArray, currentWinId }
      return datas
    },
    props: {
      config: {
        type: Object,
        default () {
          return {}
        }
      },
      newMsg: {
        type: Object,
        default () {
          return {}
        }
      },
      /* 获取新信息聊天api */
      getNewMsg: {
        type: Function,
        default: getNewMsg
      },
      /* 获取聊天会话api */
      getChatInfo: {
        type: Function,
        default: getChatInfo
      },
      /* 发送消息api */
      sendTextMsg: {
        type: Function,
        default: sendTextMsg
      }
    },
    computed: {},
    methods: {
      layIMInit () {
        layuiInit().then((layim) => {
          this.layim = layim
          layimConf.isGetNewMsg = true
          if (layimConf.isFirst) {
            layim.on('ready', (res) => {
              this.newMsgFactorial()
            })
            layim.on('chatChange', (res) => {
              if (res.data.id && res.data.id !== this.currentWinId) {
                this.currentWinId = res.data.id
                let param = { type: res.data.type, id: res.data.username, page: 1, pageSize: 20 }
                this.chatInfo(param)
              }
            })
            layim.on('sendMessage', (res) => {
              this.sendTextMsgAction(res)
            })
          }
        }).then(() => {
          let layImConfig = {
            min: false,
            isAudio: true,
            isVideo: true
          }
          if (this.config) {
            layImConfig = Object.assign(layImConfig, this.config)
          }
          this.layim.config(layImConfig)
        }).catch((err) => {
          console.error('layim:' + err)
        })
      },
      newMsgFactorial () {
        setTimeout(() => {
          if (layimConf.isGetNewMsg) {
            this.checkNewMsg()
            this.newMsgFactorial()
          }
        }, 5000)
      },
      checkNewMsg () {
        this.getNewMsg().then((res) => {
          if (+res.data.isSuccess !== 1) {
            return
          }
          let resData = res.data.data
          if (resData.friend.length > 0) {
            resData.friend.forEach((item) => {
              // if (this.newMsgArray.indexOf(item.time + item.loginName) < 0) {
              //   this.newMsgArray.push(item.time + item.loginName)
              // } else {
              //   return
              // }
              let param = { type: 'friend', id: item.loginName }
              this.chatInfo(param)
              // type 1 文字 2 声音 3图片
              let content = item.content
              if (+item.type === contentType.image) {
                content = JSON.parse(item.content).url
              }
              if (+item.type === contentType.voice) {
              }
              this.layim.getMessage({
                username: item.loginName,
                avatar: item.headIco,
                id: item.fromUserId,
                type: 'friend',
                content: content,
                timestamp: +moment(item.time)
              })
            })
          }
        })
      },
      /**
       * TODO(获取聊天信息)
       * @param :::
       * @return result:::
       * @auther zhangQ
       * @date 2018/3/11 23:15
       **/
      chatInfo (param) {
        // chatType
        if (!param.id || !param.type) {
          return
        }
        this.getChatInfo(param).then((res) => {
          if (+res.data.isSuccess !== 1) {
            return
          }
          let resData = res.data
          console.log('chatInfo', resData)
        })
      },
      /**
       * TODO(发送聊天信息)
       * @param :::
       * @auther zhangQ
       * @date 2018/3/12 11:00
       **/
      sendTextMsgAction (param) {
        this.sendTextMsg({ toUserId: param.to.name, content: param.mine.content }).then((res) => {
          let resData = res.data
          if (+resData.isSuccess !== 1) {
            console.error('发送消息错误:', res)
          }
        })
      },
      layimDestroy () {
        layimConf.isGetNewMsg = false
        this.newMsgArray = []
        this.currentWinId = ''
        // 每次关闭时销毁历史记录
        delete this.layim
        deleteCurrentChatlog()
        $('body').children('div.layui-layer').remove()
        $('body').children('div.layui-layer-move').remove()
      },
      layimMin () {
        this.layim.setChatMin()
      }
    },
    mounted () {
      this.layIMInit()
    },
    beforeDestroy () {
      this.layimDestroy()
    },
    components: {}
  }
</script>
<style scoped>

</style>
